package cn.redis;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

/**
 * http://blog.csdn.net/albertfly/article/details/51478061
 */
public class TopicMessageListener implements MessageListener {

    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {

        byte[] body = message.getBody();//请使用valueSerializer
        byte[] byteChannel = message.getChannel();
        String channel = (String)redisTemplate.getStringSerializer().deserialize(byteChannel);

        if (channel.equals("user:topic")) {
            String itemValue = (String)redisTemplate.getValueSerializer().deserialize(body);

            System.out.println("itemValue"+itemValue+",channel="+channel);
        }
        //请参考配置文件，本例中key，value的序列化方式均为string。
        //其中key必须为stringSerializer。和redisTemplate.convertAndSend对应

        System.out.println("itemValue="+",channel="+channel);
    }
}
